package com.benjaminwan.read.free.app

import android.app.Application
import android.util.Log
import com.benjaminwan.read.free.utils.initXToast
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.LogStrategy
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import com.xuexiang.xui.XUI
import io.reactivex.plugins.RxJavaPlugins
import me.jessyan.autosize.AutoSizeConfig

class App : Application() {

    companion object {
        lateinit var INSTANCE: App
    }

    override fun onCreate() {
        super.onCreate()
        INSTANCE = this
        initXUI()
        initLogger()
        initAutoSize()
        initXToast()
        RxJavaPlugins.setErrorHandler {
            Logger.e(it.message ?: "RxJavaError")
            it.printStackTrace()
        }
    }

    private fun initXUI() {
        XUI.init(this)
        XUI.debug(false)
    }

    private fun initAutoSize() {
        AutoSizeConfig.getInstance()
            .setExcludeFontScale(true)//是否屏蔽系统字体大小对 AndroidAutoSize 的影响, 如果为 true, App 内的字体的大小将不会跟随系统设置中字体大小的改变
            .setLog(false)////是否打印 AutoSize 的内部日志
    }

    private fun initLogger() {
        val formatStrategy = PrettyFormatStrategy.newBuilder()
            .showThreadInfo(true)
            .tag("ReadFree")
            .logStrategy(LogCatStrategy())
            .build()
        Logger.addLogAdapter(object : AndroidLogAdapter(formatStrategy) {
            override fun isLoggable(priority: Int, tag: String?): Boolean = false
        })
    }

    inner class LogCatStrategy : LogStrategy {

        private var last: Int = 0

        override fun log(priority: Int, tag: String?, message: String) {
            Log.println(priority, randomKey() + tag!!, message)
        }

        private fun randomKey(): String {
            var random = (10 * Math.random()).toInt()
            if (random == last) {
                random = (random + 1) % 10
            }
            last = random
            return random.toString()
        }
    }
}